package com.fgs.common.progress;

import android.content.Context;
import android.util.Log;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
/**
 * @author fgs
 * @date 2020/3/27
 **/

/**
 * 观察者
 */
public class ProgressObserver<T> implements Observer<T>, ProgressCancelListener {
    private static final String TAG = "ProgressObserver____ ";
    private ObserverResponseListener listener;
    private ProgressDialogHandler mProgressDialogHandler;
    private Disposable d;

    public ProgressObserver(Context context, ObserverResponseListener listener, boolean isDialog, boolean cancelable) {
        this.listener = listener;
        if (isDialog) {
            mProgressDialogHandler = new ProgressDialogHandler(context, this, cancelable);
        }
    }

    private void showProgressDialog() {
        if (mProgressDialogHandler != null) {
            mProgressDialogHandler.showProgressDialog();
        }
    }

    private void dismissProgressDialog() {
        if (mProgressDialogHandler != null) {
            mProgressDialogHandler.dismissProgressDialog();
            mProgressDialogHandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    public void onSubscribe(Disposable d) {
        this.d = d;
        Log.e(TAG, "onSubscribe: ");
        showProgressDialog();
//        EspressoIdlingResource.increment();
    }

    @Override
    public void onNext(T t) {
//        dismissProgressDialog();
        listener.onNext(t);//可定制接口，通过code回调处理不同的业务

    }

    @Override
    public void onError(Throwable e) {
//        EspressoIdlingResource.decrement();
        dismissProgressDialog();
        Log.e(TAG, "onError: ", e);

        //自定义异常处理
        listener.onError(ExceptionHandle.handleException(e));

//        if (e instanceof UnknownHostException) {
//            ToastUtil.showLongToast("请打开网络");
//        } else if (e instanceof SocketTimeoutException) {
//            ToastUtil.showLongToast("请求超时");
//        } else if (e instanceof ConnectException) {
//            ToastUtil.showLongToast("连接失败");
//        } else if (e instanceof HttpException) {
//            ToastUtil.showLongToast("请求超时");
//        } else if (e instanceof JsonParseException
//                || e instanceof JSONException
//                || e instanceof ParseException) {
//            ToastUtil.showLongToast("解析数据失败");
//        } else {
//            if (!CommonApplication.isLoginStatusFail) {
//                ToastUtil.showLongToast("请求失败");
//            } else {
//                CommonApplication.isLoginStatusFail = false;
//            }
//        }
    }

    @Override
    public void onComplete() {
//        EspressoIdlingResource.decrement();
        dismissProgressDialog();
        Log.e(TAG, "onComplete: ");
    }

    @Override
    public void onCancelProgress() {
        Log.e(TAG, "requestCancel: ");
        //如果处于订阅状态，则取消订阅
        if (!d.isDisposed()) {
            d.dispose();
        }
    }
}
